import * as R from 'ramda';

import { Button, Modal, Popconfirm, Space, message } from 'antd';
import { ButtonEnum, UserStatus, userStatusOptionns } from '../../../lib/enums';
import React, { useCallback, useMemo, useRef } from 'react';
import {
  createUser,
  deleteUser,
  disableUser,
  enableUser,
  getUserDetail,
  getUserList,
  recycleSuperAdmin,
  resetPassword,
  setSuperAdmin,
  updateUser,
} from '../../../service/user';
import {
  formatterTime,
  optionsToValueEnum,
  paginationWrapper,
  unResWrapper,
} from '../../../utils/common';

import AuthButton from '../../../containers/AuthButton';
import ConfirmButton from '../../../components/ConfirmButton';
import EnumTag from '../../../components/EnumTag';
import ProTable from '@ant-design/pro-table';
import UserForm from './UserForm';
import { useAuth } from '../../../store/modules/auth';
import { useButtonPermission } from '../../../hooks/permissions';
import useCRUD from '../../../hooks/useCRUD';
import variables from '../../../lib/themeVariables';

const UserManage = () => {
  const {
    isEdit,
    form,
    openHandle,
    visible,
    confirmLoading,
    okHandle,
    close,
    removeHandle,
    fetchList,
    actionRef,
  } = useCRUD({
    listService: paginationWrapper(getUserList),
    createService: unResWrapper(createUser),
    updateService: unResWrapper(({ id, ...data }) => updateUser(id, data)),
    getService: (data) =>
      getUserDetail(data.id)
        .then((res) => {
          return res.data;
        })
        .then((res) => {
          res.roleIdList = res.roleList.map((item) => item.id);
          return res;
        }),
    deleteService: unResWrapper(deleteUser),
    messages: {
      create: '创建用户成功',
      update: '更新用户成功',
      remove: '删除用户成功',
    },
  });
  const { userInfo } = useAuth();
  const title = useMemo(() => (isEdit ? '编辑用户' : '创建用户'), [isEdit]);

  const onSuccess = useCallback(() => {
    message.success('操作成功');
    actionRef.current?.reload();
  }, [actionRef]);

  const {
    hasDisableUserAuthority,
    hasEnableUserAuthority,
    hasSetSuperAdminAuthority,
    hasRecycleSuperAdminAuthority,
    hasResetPasswordAuthority,
    hasDeleteUserAuthority,
  } = useButtonPermission();

  const columns = [
    { title: '用户名', dataIndex: 'username', fixed: 'left', width: 150 },
    {
      title: '手机号码',
      render: (_, v) => v.email || '暂无数据',
      copyable: true,

      width: 150,
    },
    {
      title: '邮箱地址',
      render: (_, v) => v.email || '暂无数据',
      copyable: true,

      width: 200,
    },
    {
      title: '用户状态',
      dataIndex: 'status',
      valueEnum: optionsToValueEnum(userStatusOptionns.getOptions()),
      render: (_, v) => <EnumTag.UserTag value={v.status} />,
    },
    {
      title: '绑定的角色数',
      dataIndex: 'roleList',
      search: false,
      render: R.length,
    },
    {
      title: '最近登录ip',
      render: (_, v) => v.lastLoginIp || '暂无登录',
      search: false,
    },
    {
      title: '最近登录时间',
      render: (_, v) =>
        v.lastLoginAt ? formatterTime(v.lastLoginAt) : '暂未登录',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      render: formatterTime,
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      render: formatterTime,
      search: false,
    },
    {
      title: '操作',
      search: false,
      width: 200,
      fixed: 'right',
      render: (_, row) => {
        const isSelf = row.id === userInfo.id;
        return (
          <Space>
            <AuthButton
              code={ButtonEnum.UPDATED_USER}
              size="small"
              type="link"
              onClick={() => openHandle(row)}
            >
              编辑
            </AuthButton>
            {row.status === UserStatus.DISABLED &&
              !isSelf &&
              hasEnableUserAuthority && (
                <ConfirmButton
                  confirmProps={{ title: `确定启用用户【${row.username}】?` }}
                  buttonProps={{ size: 'small', type: 'link' }}
                  text="启用"
                  service={() => enableUser(row.id)}
                  onSuccess={onSuccess}
                />
              )}
            {row.status === UserStatus.ENABLED &&
              !isSelf &&
              hasDisableUserAuthority && (
                <ConfirmButton
                  confirmProps={{ title: `确定禁用用户【${row.username}】?` }}
                  buttonProps={{ size: 'small', type: 'link' }}
                  text="禁用"
                  onSuccess={onSuccess}
                  service={() => disableUser(row.id)}
                />
              )}
            {!row.isSuperAdmin && hasSetSuperAdminAuthority && (
              <ConfirmButton
                confirmProps={{
                  title: `确定将用户【${row.username}】设置为超管?`,
                }}
                buttonProps={{ size: 'small', type: 'link' }}
                text="设为超管"
                service={() => setSuperAdmin(row.id)}
                onSuccess={onSuccess}
              />
            )}
            {row.isSuperAdmin && hasRecycleSuperAdminAuthority && (
              <ConfirmButton
                confirmProps={{
                  title: `确定回收用户【${row.username}】的超管?`,
                }}
                buttonProps={{ size: 'small', type: 'link' }}
                text="回收超管"
                service={() => recycleSuperAdmin(row.id)}
                onSuccess={onSuccess}
              />
            )}
            {hasResetPasswordAuthority && (
              <ConfirmButton
                confirmProps={{ title: `确定删除用户【${row.username}】?` }}
                buttonProps={{ size: 'small', type: 'link' }}
                text="重置密码"
                service={() => resetPassword(row.id)}
                onSuccess={onSuccess}
              />
            )}
            {hasDeleteUserAuthority && !isSelf && (
              <ConfirmButton
                confirmProps={{ title: `确定删除用户【${row.username}】?` }}
                buttonProps={{ size: 'small', type: 'text', danger: true }}
                text="删除"
                service={() => removeHandle(row)}
              />
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <div style={{ margin: variables.space }}>
      <Modal
        visible={visible}
        width="70%"
        onOk={okHandle}
        confirmLoading={confirmLoading}
        onCancel={close}
        title={title}
        destroyOnClose
      >
        <UserForm form={form} editable={isEdit} />
      </Modal>

      <ProTable
        actionRef={actionRef}
        request={(...args) => fetchList(...args)}
        rowKey="id"
        scroll={{
          x: '130%',
        }}
        columns={columns}
        toolBarRender={() => [
          <AuthButton
            code="CREATE_USER"
            key="create"
            type="primary"
            onClick={() => openHandle()}
          >
            创建用户
          </AuthButton>,
        ]}
      />
    </div>
  );
};

export default UserManage;
